package com.rongke.sms;

import com.rongke.redis.CacheUtil;
import com.rongke.utils.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by bilibili on 2017/8/30.
 */
@Component
public class SmsUtilImpl implements SmsUtil {

    @Autowired
    private CacheUtil cacheUtil;

    private static final String ACCOUNT = "miduoduo";
    private static final String PWD = "Miduoduo1";
    private static final String URL = "https://sapi.253.com/msg/HttpBatchSendSM";




    /**
     * 发送验证码
     * @param phone 电话号码
     * @return
     * @throws Exception
     */
    public  Boolean sendCode(String phone)  {
        String code = RandomUtils.randomString(6);
        String msg = "您好,您的验证码是"+code+" 请于2分钟内正确输入。";
        String url = "http://sapi.253.com/msg/";// 应用地址
//        String mobile = "13800210021,13800138000";// 手机号码，多个号码使用","分割
        boolean needstatus = true;// 是否需要状态报告，需要true，不需要false
        String extno = null;// 扩展码
        Boolean flag=false;
        try {
            String returnString = HttpSender.batchSend(url, ACCOUNT, PWD, phone, msg, needstatus, extno);
            String str[] =returnString.split("\n");
            if("0".equals(str[0].split(",")[1])){
                if(cacheUtil.hasKey(phone)){
                    cacheUtil.delkey(phone);
                }
                cacheUtil.set(phone,code,120L);
                flag=true;
            }
            System.out.println(returnString);
            // TODO 处理返回值,参见HTTP协议文档

        } catch (Exception e) {
            // TODO 处理异常
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 校验验证码
     * @param phone 手机号码
     * @param code  验证码
     * @return true表示成功，false表示失败
     * @throws Exception
     */
    public  Boolean checkCode(String phone,String code)  {
        Boolean flag=cacheUtil.hasKey(phone);
        if(!flag){
            return false;
        }
        String resultCode = cacheUtil.getStr(phone,true);
        if(resultCode == null || "".equals(resultCode) || !resultCode.equals(code)){
            return false;
        }else{
            return true;
        }

    }


}
